﻿using MediatR;
using T.Settlement.Domain;
using T.Settlement.Domain.DTO;
using T.Settlement.Read.API.Application.Command.InvoiceCommand;
using T.Settlement.Repository.SettlementInterface;

namespace T.Settlement.Read.API.Application.CommandHandlers.InvoiceHandler
{
    public class InvoiceShowCommandHandler : IRequestHandler<InvoiceShowCommand, SListDTO<Invoice>>
    {
        private readonly IInvoiceSRepository _invoiceSRepository;
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="invoiceSRepository"></param>
        public InvoiceShowCommandHandler(IInvoiceSRepository invoiceSRepository)
        {
            _invoiceSRepository = invoiceSRepository;
        }

        public async Task<SListDTO<Invoice>> Handle(InvoiceShowCommand request, CancellationToken cancellationToken)
        {
            var list = (await _invoiceSRepository.GetAllAsync()).Where(x=>!x.IsDeleted);
            if (!string.IsNullOrEmpty(request.CustomerName))
            {
                list=list.Where(x=>x.CustomerName.Contains(request.CustomerName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.InvoicingUnit))
            {
                list=list.Where(x=>x.InvoicingUnit.Contains(request.InvoicingUnit)).ToList();
            }
            if (request.InvoiceType != 0)
            {
                list = list.Where(x => x.InvoiceType == request.InvoiceType).ToList();
            }
            if (request.InvoicingDate != null)
            {
                list=list.Where(x=>x.InvoicingDate==Convert.ToDateTime(request.InvoicingDate).AddDays(1)).ToList();
            }
            if (request.InvoiceClassify != 0)
            {
                list=list.Where(x=>x.InvoiceClassify==request.InvoiceClassify).ToList();
            }
            if (!string.IsNullOrEmpty(request.CompanyID))
            {
                list = list.Where(x => x.CompanyID == request.CompanyID).ToList();
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize == null)
            {
                request.PageSize = list.Count();
            }
            SListDTO<Invoice> page=new SListDTO<Invoice>();
            page.TotalCount = list.Count();
            page.TotalPage = (int)Math.Ceiling((double)((page.TotalCount * 1.0) / request.PageSize));
            page.List=list.OrderByDescending(x=>x.CreatedDate).Skip((int)((request.PageIndex - 1) * request.PageSize)).Take((int)request.PageSize).ToList();
            return page;
        }
    }
}
